package com.zhang.modules.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zhang.checker.TokenGenerator;
import com.zhang.common.jpa.entity.DTO;
import com.zhang.common.jpa.service.impl.BaseServiceImpl;
import com.zhang.constants.UserConstant;
import com.zhang.exception.exception.NormalException;
import com.zhang.modules.user.entity.SysUser;
import com.zhang.modules.user.entity.cmd.LoginCmd;
import com.zhang.modules.user.entity.dto.SysUserDto;
import com.zhang.modules.user.rep.SysUserRep;
import com.zhang.modules.user.service.ISysUserService;
import com.zhang.modules.user.service.PasswordEncoder;
import com.zhang.principal.impl.SimpleUserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SysUserService extends BaseServiceImpl<SysUserRep, SysUser,String> implements ISysUserService {

    private PasswordEncoder passwordEncoder;

    private TokenGenerator tokenGenerator;

    public SysUserService(PasswordEncoder passwordEncoder, TokenGenerator tokenGenerator) {
        this.passwordEncoder = passwordEncoder;
        this.tokenGenerator = tokenGenerator;
    }




    @Override
    public SysUser save(SysUser user) {
        String salt = RandomUtil.randomString(5);
        String encode = passwordEncoder.encode(user.getPassword()+salt);
        user.setPasswordSalt(salt);
        user.setPassword(encode);
        return super.save(user);
    }


    @Override
    public String login(LoginCmd cmd) {
        SysUser user = getRep().findByUserAccountEquals(cmd.getUserAccount());

        //校验密码是否正确
        if (!passwordEncoder.match(cmd.getPassword()+user.getPasswordSalt(),user.getPassword())){
            throw new NormalException("密码错误");
        }
        if (user.getStatus().equals(UserConstant.USER_STATUS_LOCK)) throw new NormalException("用户被锁定");

        SimpleUserInfo userInfo = new SimpleUserInfo();
        //设置用户角色，id
        Set<String> roleStrs = new HashSet<>();
        user.getRoles().forEach(role ->{
            roleStrs.add(role.getId());
        });
        userInfo.setRoles(roleStrs);
        userInfo.setId(user.getId());

        String token = tokenGenerator.createToken(userInfo);

        return token;
    }





    @Override
    public <R extends DTO> R convert2DtoSingle(SysUser orginInfo) {
        R userDto = (R) new SysUserDto();
        BeanUtils.copyProperties(orginInfo,userDto);
        return userDto;
    }



}
